<?php
class Tourismgoodsbargaining extends CS_Controller
{
    private $uidArray = array();
    
    public function _init(){
        $this->load->library('pagination');
        $this->load->model('tourism_goods_bargaining_model', 'tourism_goods_bargaining');
        $this->load->model('tourism_goods_base_model', 'tourism_goods_base');
        $this->load->model('user_model', 'user');
        $this->load->model('user_type_model', 'user_type');
        $this->load->model('user_account_model','user_account');
    }
    
    public function grid($pg = 1){
        $num = ($pg-1)*20;
        $page_num = 20;
        $goodsAttrId = $this->input->get('goods_attr_id');
        $config['base_url']    = base_url('tourismgoodsbargaining/grid');
        $config['total_rows']  = $this->tourism_goods_bargaining->total($goodsAttrId);
        $config['uri_segment'] = 3;
        $this->pagination->initialize($config);
        $data['pg_list']   = $this->pagination->create_links();
        $data['page_list'] = $this->tourism_goods_bargaining->page_list($num,$page_num,$goodsAttrId);
        $data['all_rows']  = $config['total_rows'];
        $data['pg_now']    = $pg;
        $this->load->view('tourismgoodsbargaining/grid', $data);
    }
    
    public function add(){
        $goods_attr_id = $this->input->get('goods_attr_id');
        $result = $this->tourism_goods_base->getGoodsAttr($goods_attr_id);
        if($result->num_rows() <= 0){
            $this->error('tourismgoodsbase/grid', '', '该商品不存在');
        }
        $data['tourismgoodsbase'] = $result->row();
        $this->load->view('tourismgoodsbargaining/add',$data);
    }
    
    public function addPost(){
        $user = $this->user_account->findOne(['uid'=>$this->uid])->row();
        if (empty($user)){
            $this->error('tourismgoodsbargaining/add', '', '供应商账户不存在');
        }
        $poundage = $user->poundage;
        $data = $this->input->post();
        $data['poundage'] = bcmul($this->input->post('shop_price'), $poundage,2);
        $data['supply_price'] = bcsub($this->input->post('shop_price'), $data['poundage'],2);
        $data['provider_uid'] = $this->uid;
        
        $this->db->trans_start();
        foreach ($this->uidArray as $key=>$value) {
            $barganiningId = $this->tourism_goods_bargaining->add($data,$key);
        }
        $this->db->trans_complete();
        
        if ($this->db->trans_status() === FALSE) {
            $this->session->set_flashdata('error', '保存失败！');
            $this->jsen('tourismgoodsbargaining/grid?goods_attr_id='.$this->input->post('goods_attr_id'), true);
        } else {
            $this->session->set_flashdata('success', '保存成功！');
            $this->jsen('tourismgoodsbargaining/grid?goods_attr_id='.$this->input->post('goods_attr_id'), true);
        }
    }
    
    public function upOrDown($id){
        $status = $this->input->get('status');
        switch ($status) {
            case 1:
            $flag = 0;
            break;
            case 0:
            $flag = 1;
            break;
            
            default:
            $flag = 1;
            break;
        }
        $res = $this->tourism_goods_bargaining->update(['status'=>$flag],['bargaining_id'=>$id,'provider_uid'=>$this->uid]);
        if (!$res){
            $this->error('tourismgoodsbargaining/grid', array('goods_attr_id'=>$this->input->get('goods_attr_id')), '修改失败');
        }
        $this->success('tourismgoodsbargaining/grid', array('goods_attr_id'=>$this->input->get('goods_attr_id')), '修改成功');
    }
    
    public function delete($id){
        $this->db->trans_start();
        $is_delete = $this->tourism_goods_bargaining->delete($id);
        $this->db->trans_complete();
        if ($is_delete)
        {
            $this->success('tourismgoodsbargaining/grid', array('goods_attr_id'=>$this->input->get('goods_attr_id')), '删除成功！');
        } else {
            $this->error('tourismgoodsbargaining/grid', array('goods_attr_id'=>$this->input->get('goods_attr_id')), '删除失败！');
        }
    }
    
    public function ajaxValidate()
    {
        //是否存在这些用户
        $error = $this->validateUserName();
        if (!empty($error)) {
            $this->jsen($error);
        }
        //验证这些用户是否议过价
        $error = $this->validateSeller();
        if (!empty($error)) { //如果不为空，则此用户议过价
            $this->jsen($error);
        }
        //验证数据的正确性
        $error = $this->validataPostInfo();
        if (!empty($error)) {
            $this->jsen($error);
        }
        
        $this->addPost();
    }
    
    private function jsen($error, $flag=false)
    {
        if (is_array($error)) {
            $erro = '';
            foreach ($error as $er) {
                $erro .= '<p>'. $er . '</p>';
            }
            $error = $erro;
        }
        echo json_encode(array(
                'status'=> $flag,
                'msg'   => $error
        ));exit;
    }
    
    public function validateUserName()
    {
        $error = array();
        $seller_name = trim(strtr($this->input->post('user_name'), array('，'=>',')), ',');
        if (strpos($seller_name, ',') === false) {
            $sellerArray = $seller_name;
        } else {
            $sellerArray = explode(',', $seller_name);
        }
        if (empty($sellerArray)) {
            return $error[] = '分销商不可为空！';
        }
        if (!is_array($sellerArray)) {
            $sellerArray = array($sellerArray);
        }
        $phoneArr = array();
        $nameArr = array();
        $phoneIdArr = array();
        $nameIdArr = array();
        foreach ($sellerArray as $value) {
            if (validateMobilePhone($value)){
                $phoneArr[] = $value;
            } else {
                $nameArr[] = $value;
            }
        }
        
        if (!empty($phoneArr)){
            $resultUtitSeller = $this->user->findByIds(array('mobile_phone' => $phoneArr, 'user_type' => UTID_SELLER)); //用户类型为分销商
            if (!$resultUtitSeller) {
                return $error[] = implode($phoneArr, ',').'分销商用户不存在！';
            }
            $phoneIdArr = $this->getUserPhoneUid($resultUtitSeller);
            $diffArray = array_diff($phoneArr, $phoneIdArr);
            if (!empty($diffArray)) {
                return $error[] = '分销商为 "'.implode($diffArray, ',').'" 的用户不存在';
            }
        }
        
        if (!empty($nameArr)){
            $resultUtitSeller = $this->user->findByIds(array('user_name' => $nameArr, 'user_type' => UTID_SELLER)); //用户类型为分销商
            if (!$resultUtitSeller) {
                return $error[] = implode($nameArr, ',').'分销商用户不存在！';
            }
            $nameIdArr= $this->getUserNameUid($resultUtitSeller);
            $diffArray = array_diff($nameArr, $nameIdArr);
            if (!empty($diffArray)) {
                return $error[] = '分销商为 "'.implode($diffArray, ',').'" 的用户不存在';
            }
        }
        $this->uidArray = $phoneIdArr + $nameIdArr;
        return $error;
    }
    
    private function getUserPhoneUid($result)
    {
        $sellerQuery = array();
        foreach ($result->result() as $item) {
            $sellerQuery[$item->uid] = $item->mobile_phone;
        }
        return $sellerQuery;
    }
    
    private function getUserNameUid($result)
    {
        $sellerQuery = array();
        foreach ($result->result() as $item) {
            $sellerQuery[$item->uid] = $item->user_name;
        }
        return $sellerQuery;
    }
    
    public function validateSeller()
    {
        $error = array();
        $goodsAttrId = $this->input->post('goods_attr_id');
        if (!$goodsAttrId) {
            return $error[] = '产品编号丢失，请重新操作。';
        }
        $result = $this->tourism_goods_bargaining->findByArray(array('goods_attr_id'=>$goodsAttrId, 'seller_uid'=>array_keys($this->uidArray)));
        
        $userName = array();
        if ($result) {
            foreach ($result->result() as $value) {
                $userName[] = array_search($value->seller_uid, array_keys($this->uidArray));
            }
        }
        if (!empty($userName)) {
            return $error[] = '用户 "'.implode(',', $userName).'" 已经议过价了.';
        }
        return $error;
    }
    
    public function validataPostInfo()
    {
        $error = array();
        if (!is_numeric($this->input->post('shop_price')) || $this->input->post('shop_price') <= 0) {
            $error[] = '分销价不可为空，只能为大于零的数字。';
        }
        if ($this->input->post('shop_price') >= $this->input->post('old_price')){
            $error[] = '分销价必须小于销售价格。';
        }
        return $error;
    }
}